package rwt.server.handlers.web;

import static rwt.server.WebMessages.*;

import java.io.*;
import java.util.concurrent.TimeoutException;

import org.slf4j.*;

import rwt.server.*;
import rwt.server.RailroadMessages.DoReadLayoutMsg;
import rwt.server.WebMessages.ChangeSystemStatus;
import rwt.server.WebMessages.PutSystemStatus;
import rwt.server.core.*;

public class ChangeSystemStatusHandler extends MessageHandler<ChangeSystemStatus>
{
	private static final Logger logger = LoggerFactory.getLogger(ChangeSystemStatusHandler.class);
	
	@Override
	public void handle(ChangeSystemStatus message, IConnection source) throws Exception
	{
		if (message.systemStatus == SYSTEM_STATUS_RUNNING)
		{
			startSystem();
		}
		else if (message.systemStatus == SYSTEM_STATUS_STOPPED)
		{
			stopSystem();
		}
	}
	
	private void startSystem() throws Exception
	{
		logger.info("--- Starting system! ---");
		RailServer.getClientManager().sendToAll(new PutSystemStatus(SYSTEM_STATUS_STARTING));
		
		Thread startControllerThread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					RailServer.getController().start();
				}
				catch (Exception e)
				{
					logger.warn("", e);
				}
			}
		});
		
		Thread startRailServerThread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					RailServer.getRailroadServer().start();
				}
				catch (Exception e)
				{
					logger.warn("", e);
				}
			}
		});
		
		startControllerThread.start();
		startRailServerThread.start();
		
		startControllerThread.join();
		startRailServerThread.join();
		
		DoReadLayoutMsg readLayoutMsg = new DoReadLayoutMsg(Config.layoutXmlFile.getPath());
		RailServer.getController().write(readLayoutMsg);
		
		RailServer.getClientManager().sendToAll(new PutSystemStatus(SYSTEM_STATUS_RUNNING));
	}
	
	private void stopSystem() throws IOException, InterruptedException, TimeoutException
	{
		logger.info("--- Stopping system! ---");
		RailServer.getClientManager().sendToAll(new PutSystemStatus(SYSTEM_STATUS_STOPPING));
		
		executeScript(Config.shutdownScriptFile);
		logger.info("--- Shut-down script finished ---");
		
		RailServer.getController().resetConnection();
		RailServer.getRailroadServer().resetConnection();
		RailServer.getTrainManager().reset();
		RailServer.getSwitchManager().reset();
		RailServer.getClientManager().sendToAll(RailServer.getTrainManager().getPutAvailableTrains());
		RailServer.getClientManager().sendToAll(new PutSystemStatus(SYSTEM_STATUS_STOPPED));
	}
	
	private void executeScript(File scriptFile) throws IOException, InterruptedException
	{
		if (!scriptFile.isFile())
			throw new FileNotFoundException("Script '" + scriptFile + "' not found! Double-check config.");
		
		Process p = Runtime.getRuntime().exec("cmd /c \"" + scriptFile.getAbsolutePath() + "\"", null,
				scriptFile.getParentFile());
		p.waitFor();
	}
}
